﻿using System;
using System.Web.UI.WebControls;
using Resources;
using Wicresoft.RDW.Presentation;
using Wicresoft.RDW.Utility;

namespace Wicresoft.RDW.LabManage
{
    public partial class Update : BasePage_BackEnd
    {
        private static int labcloseid = 0;
        private static bool startSoonerToday = false;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                startSoonerToday = false;
                InitData();
            }
        }

        protected void InitData()
        {
            lblStartTimeError.Text = string.Empty;
            lblEndTimeError.Text = string.Empty;
            lblReasonError.Text = string.Empty;
            lblOtherReasonError.Text = string.Empty;
            divComments.Visible = false;
            ddlReason.DataSource = ReasonPresent.GetList();
            ddlReason.DataTextField = Language == Language.CN ? "Desc_CN" : "Desc_EN";
            ddlReason.DataValueField = "ReasonId";
            ddlReason.DataBind();
            ddlReason.Items.Insert(0, new ListItem(CommonResource.PleaseSelect, "-1"));
            ddlReason.Items.Add(new ListItem(NameResource.LabCloseSchedule_Others, "-2"));
            if (string.Equals(GetQueryString("pageStatus"), "edit", StringComparison.CurrentCultureIgnoreCase))
            {
                var labCloseSchedule = LabCloseSchedulePresent.GetById(Id);
                labcloseid = Id;
                if (labCloseSchedule != null)
                {
                    var lab = LabPresent.GetById(labCloseSchedule.LabId);
                    if (lab != null)
                    {
                        ucLocationLab.LocationValue = lab.LocationId.ToString();
                        ucLocationLab.LabValue = lab.LabId.ToString();
                    }
                    txtSartDate.Text = labCloseSchedule.StartDate.ToString("yyyy-MM-dd");
                    txtEndDate.Text = labCloseSchedule.EndDate.ToString("yyyy-MM-dd");
                    if (labCloseSchedule.ReasonId <= 0)
                    {
                        ddlReason.SelectedValue = "-2";
                        txtOtherReason.Text = labCloseSchedule.OtherReason;
                        divOtherReason.Visible = true;
                    }
                    else
                    {
                        ddlReason.SelectedValue = labCloseSchedule.ReasonId.ToString();
                        divOtherReason.Visible = false;
                    }
                    txtSolutionCN.Text = labCloseSchedule.Solution_CN;
                    txtSolutionEN.Text = labCloseSchedule.Solution_EN;
                    var starDate = Convert.ToDateTime(txtSartDate.Text);
                    if (DateTime.Compare(starDate, DateTime.Today) < 0)
                    {
                        ucLocationLab.Enabled = false;
                        txtSartDate.Enabled = false;
                        txtEndDate.Enabled = true;
                        ddlReason.Enabled = false;
                        txtOtherReason.Enabled = false;
                        txtSolutionCN.Enabled = false;
                        txtSolutionEN.Enabled = false;
                        startSoonerToday = true;
                    }
                    PageStatus = Utility.PageStatus.Edit;
                }
                else { this.phClose.Visible = false; }
            }
            else if (string.Equals(GetQueryString("pageStatus"), "new", StringComparison.CurrentCultureIgnoreCase))
            {
                txtSartDate.Text = string.Empty;
                txtEndDate.Text = string.Empty;
                ddlReason.SelectedValue = "-1";
                txtOtherReason.Text = string.Empty;
                txtSolutionCN.Text = string.Empty;
                txtSolutionEN.Text = string.Empty;
                PageStatus = Utility.PageStatus.New;
            }
            else
            { this.phClose.Visible = false; }
        }

        public override void InitControlResource()
        {
            btnSubmit.Text = ManageResource.mgr_btnOK;
            btnCancelClose.Text = ManageResource.mgr_btnCancel;
            rfvtxtSartDate.ErrorMessage = NameResource.StartTime + CommonResource.NotNull;
            rfvtxtEndDate.ErrorMessage = NameResource.EndTime + CommonResource.NotNull;
            rfvtxtSolutionCN.ErrorMessage = NameResource.LabCloseSchedule_Solution_CN + CommonResource.NotNull;
            rfvtxtSolutionEN.ErrorMessage = NameResource.LabCloseSchedule_Solution_EN + CommonResource.NotNull;
            revtxtOtherReason.Text = string.Format(NameResource.OverMaxLength, "100");
            revtxtSolutionCN.Text = string.Format(NameResource.OverMaxLength, "200");
            revtxtSolutionEN.Text = string.Format(NameResource.OverMaxLength, "200");
        }

        protected void ddlReason_SelectedIndexChanged(object sender, EventArgs e)
        {
            int reasonid = int.Parse(this.ddlReason.SelectedValue);
            if (reasonid == -2)
                divOtherReason.Visible = true;
            else
                divOtherReason.Visible = false;
            //checkinput();
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            int mailScheduleId = 0;
            if (!checkinput())
                return;
            int labid = int.Parse(ucLocationLab.LabValue);
            var starDate = Convert.ToDateTime(txtSartDate.Text);
            var endDate = Convert.ToDateTime(txtEndDate.Text);
            var solutionCN = Server.HtmlEncode(txtSolutionCN.Text);
            var solutionEN = Server.HtmlEncode(txtSolutionEN.Text);
            var otherReason = Server.HtmlEncode(txtOtherReason.Text);
            var reasonid = int.Parse(ddlReason.SelectedValue);
            switch (PageStatus)
            {
                case Utility.PageStatus.New:
                    if (reasonid == -2)
                    {
                        Model.LabCloseSchedule labCloseSchedule = new Model.LabCloseSchedule()
                        {
                            StartDate = starDate,
                            EndDate = endDate,
                            Solution_CN = solutionCN,
                            Solution_EN = solutionEN,
                            OtherReason = otherReason,
                            LabId = labid
                        };
                        LabCloseSchedulePresent.Create(labCloseSchedule);
                        mailScheduleId = labCloseSchedule.ScheduleId;
                    }
                    else
                    {
                        Model.LabCloseSchedule labCloseSchedule = new Model.LabCloseSchedule()
                        {
                            StartDate = starDate,
                            EndDate = endDate,
                            ReasonId = reasonid,
                            Solution_CN = solutionCN,
                            Solution_EN = solutionEN,
                            LabId = labid
                        };
                        LabCloseSchedulePresent.Create(labCloseSchedule);
                        mailScheduleId = labCloseSchedule.ScheduleId;
                    }
                    break;
                case Utility.PageStatus.Edit:
                    if (reasonid == -2)
                    {
                        var l = LabCloseSchedulePresent.GetById(labcloseid);
                        if (l != null)
                        {
                            l.StartDate = starDate;
                            l.EndDate = endDate;
                            l.Solution_CN = solutionCN;
                            l.Solution_EN = solutionEN;
                            l.OtherReason = otherReason;
                            l.LabId = labid;
                            LabCloseSchedulePresent.Update(l);
                        }
                    }
                    else
                    {
                        var l = LabCloseSchedulePresent.GetById(labcloseid);
                        if (l != null)
                        {
                            l.StartDate = starDate;
                            l.EndDate = endDate;
                            l.Solution_CN = solutionCN;
                            l.Solution_EN = solutionEN;
                            l.ReasonId = reasonid;
                            l.LabId = labid;
                            LabCloseSchedulePresent.Update(l);
                        }
                    }
                    mailScheduleId = labcloseid;
                    break;
            }

            //邮件通知，并将闭关时间段内的申请置为草稿
            toEmailNotification(starDate, endDate, labid, mailScheduleId);
            Response.Redirect("/LabManage/View.aspx");
        }

        protected bool checkinput()
        {
            int i = 0;
            lblStartTimeError.Text = string.Empty;
            lblEndTimeError.Text = string.Empty;
            lblReasonError.Text = string.Empty;
            lblOtherReasonError.Text = string.Empty;
            int labid = int.Parse(ucLocationLab.LabValue);
            var starDate = Convert.ToDateTime(txtSartDate.Text);
            var endDate = Convert.ToDateTime(txtEndDate.Text);
            var reasonid = int.Parse(ddlReason.SelectedValue);
            if (reasonid == -1)
            {
                lblReasonError.Text = CommonResource.NotNull;
                lblReasonError.Visible = true;
                i++;
            }
            if (reasonid == -2 && txtOtherReason.Text.Trim() == string.Empty)
            {
                lblOtherReasonError.Text = CommonResource.NotNull;
                lblOtherReasonError.Visible = true;
                i++;
            }
            if (startSoonerToday)
            {
                if (DateTime.Compare(endDate, DateTime.Today.AddDays(-1)) < 0)
                {
                    lblEndTimeError.Text = NameResource.LabClose_EndStateError;
                    lblEndTimeError.Visible = true;
                    i++;
                    return false;
                }
            }
            else
            {
                if (DateTime.Compare(starDate, DateTime.Today) < 0)
                {
                    lblStartTimeError.Text = NameResource.LabClose_StartTimeError;
                    lblStartTimeError.Visible = true;
                    i++;
                    return false;
                }
            }
            if (DateTime.Compare(starDate, endDate) > 0)
            {
                lblEndTimeError.Text = NameResource.LabClose_EndTimeError;
                lblEndTimeError.Visible = true;
                i++;
                return false;
            }
            if (!checkExistTime(starDate, endDate, labid))
            {
                lblStartTimeError.Text = NameResource.LabClose_TimeExistError;
                lblEndTimeError.Text = NameResource.LabClose_TimeExistError;
                lblStartTimeError.Visible = true;
                lblEndTimeError.Visible = true;
                i++;
                return false;
            }

            if (i > 0) return false;
            else return true;
        }

        protected bool checkExistTime(DateTime startDate, DateTime endDate, int labid)
        {
            int count = 0;
            switch (PageStatus)
            {
                case Utility.PageStatus.New:
                    count = LabCloseSchedulePresent.GetList(g => (g.LabId == labid) && ((g.StartDate >= startDate && g.StartDate <= endDate) || (g.EndDate >= startDate && g.EndDate <= endDate))).Count;
                    break;
                case Utility.PageStatus.Edit:
                    count = LabCloseSchedulePresent.GetList(g => (g.ScheduleId != labcloseid) && (g.LabId == labid) && ((g.StartDate >= startDate && g.StartDate <= endDate) || (g.EndDate >= startDate && g.EndDate <= endDate))).Count;
                    break;
            }
            return count == 0;
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("/LabManage/View.aspx");
        }


        //邮件通知，并将闭关时间段内的申请置为草稿
        protected void toEmailNotification(DateTime startDate, DateTime endDate, int labid, int closeScheduleId)
        {
            int statusPending = (int)RequestStatus.Pending;
            int statusApproved = (int)RequestStatus.Approved;
            int statusAskForMore = (int)RequestStatus.AskForMore;
            var request = RequestPresent.GetList(g => g.RequestDate <= endDate && g.RequestDate >= startDate && g.LabId == labid && (g.Status == statusPending || g.Status == statusApproved || g.Status == statusAskForMore));
            if (request != null)
            {
                foreach (var r in request)
                {
                    var requestedit = RequestPresent.GetById(r.RequestId);
                    if (requestedit != null)
                    {
                        requestedit.Status = (int)RequestStatus.Draft;//申请改为草稿 
                        RequestPresent.Update(requestedit);
                    }

                    var user = UserPresent.GetById(r.RequestUserId);
                    if (user != null)
                    {
                        string content = string.Empty;
                        var labClose = LabCloseSchedulePresent.GetById(closeScheduleId);
                        if (labClose != null)
                        {
                            string labname = string.Empty;
                            string reasonCN = string.Empty;
                            string reasonEN = string.Empty;
                            string managerEmail = string.Empty;
                            string managerTel = string.Empty;
                            string nameCN = string.Empty;
                            string nameEN = string.Empty;
                            RequestPresent.GetUserNameById(user.UserId, out nameCN, out nameEN);
                            labname = RequestPresent.GetLabNameById(labClose.LabId);
                            reasonCN = GetReasonCNById(closeScheduleId);
                            reasonEN = GetReasonENById(closeScheduleId);
                            RequestPresent.GetEmailPhoneById(CurrentUserId,out managerEmail,out managerTel);

                            content = nameEN + "^" + labname + "^" + requestedit.RequestDate.ToString("yyy/MM/dd") + "^" + reasonEN + "^" + managerEmail + "^" + managerTel
                                + "^" + nameCN + "^" + reasonCN + "^" + requestedit.RequestDate.ToString("yyy/MM/dd") + "^" + labname + "^" + managerEmail + "^" + managerTel;
                            MailPresent.SendMail(EmailTemplate.LabClosedReminder, content, user.Email, "");
                        }
                    }
                }
            }
        }


        protected string GetReasonCNById(int scheduleid)
        {
            string reasonCN = string.Empty;
            var labClose = LabCloseSchedulePresent.GetById(scheduleid);
            if (labClose != null)
            {
                if (labClose.ReasonId > 0)
                {
                    var reason = ReasonPresent.GetById(labClose.ReasonId);
                    if (reason != null)
                    {
                        reasonCN = reason.Desc_CN;
                    }
                }
                else
                {
                    reasonCN = labClose.OtherReason;
                }
            }
            return reasonCN;
        }

        protected string GetReasonENById(int scheduleid)
        {
            string reasonEN = string.Empty;
            var labClose = LabCloseSchedulePresent.GetById(scheduleid);
            if (labClose != null)
            {
                if (labClose.ReasonId > 0)
                {
                    var reason = ReasonPresent.GetById(labClose.ReasonId);
                    if (reason != null)
                    {
                        reasonEN = reason.Desc_EN;
                    }
                }
                else
                {
                    reasonEN = labClose.OtherReason;
                }
            }
            return reasonEN;
        }


    }
}